using System;
using System.IO;
using System.Web;
using System.Data;
using System.Xml;
using System.Threading;
using System.Collections;
using System.ComponentModel;
using System.Web.Security;
using System.Web.Services;
using ACM.cmsarea08;




namespace ACM.cmsarea08.AdmFileManager {
	public class XmlServer : System.Web.Services.WebService {
		private ACM.cmsarea08.DBManager.DBClass dclass;
		private string TablePrefix;
		private const string filmanagerpath = "/public/admfmanager/";
		private string SqlText(string text) {
			return ACM.cmsarea08.Function.TextClass.textclass.SqlTesto(text);
			
		}
		
		public XmlServer() {
			dclass = new ACM.cmsarea08.DBManager.DBClass();
			TablePrefix = ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle;
		}
		
		[WebMethod]
		public XmlDocument getFiles(string idinstance){
			DataSet dvs = dclass.Helper_Dataset(" select adm.*, " +
												" utio.username as authorname from "+TablePrefix +"admfilemanager as adm " +
												" left join itant_utenti as utio on utio.id=adm.author " +
			                                    " where instanceid='"+idinstance+"' order by data_mod desc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}
		
		[WebMethod]
		public string SaveFile(string guid, string groupname, string instance,string pfilename,string related,string author) {
			if(guid.Trim().Length==0) return "000x04NG";
			if(instance.Trim().Length==0) return "000x04NI";
			guid = HttpUtility.UrlDecode(guid);
			groupname = HttpUtility.UrlDecode(groupname);
			instance  = HttpUtility.UrlDecode(instance);
			author    = HttpUtility.UrlDecode(author);
//			byte[] dati = new byte[0];
//			string filename = "";
//			if( HttpContext.Current.Cache["NAMEIMG" + guid]!=null)
//				filename = HttpContext.Current.Cache["NAMEIMG" + guid].ToString();
//			else
//				return "NF";
//			if( HttpContext.Current.Cache["DATIIMG" + guid]!=null)
//				dati =  (byte[])HttpContext.Current.Cache.Get("DATIIMG" + guid);
//			else
//				return "NO";
			
			byte[] dati = new byte[0];
			string filename = "";
			ACM.cmsarea08.Function.CacheFileObjectInfo clInfo = ACM.cmsarea08.Function.CacheManager.cachemanager.getCacheFileObjectInfo(HttpContext.Current,guid);
			if(!clInfo.exists)
				return "000x04NF";
			string fileData = ACM.cmsarea08.Function.CacheManager.cachemanager.getCacheFileObject(HttpContext.Current,guid);
			if(fileData.IndexOf('#')==-1) return "000x04NO";
			filename = clInfo.filename;
			dati = Convert.FromBase64String(fileData.Substring(fileData.IndexOf('#')+1));
			//ho i valori base.
//			System.IO.FileStream fr = new System.IO.FileStream(HttpContext.Current.Server.MapPath(filmanagerpath + guid),System.IO.FileMode.Create);
			using ( System.IO.FileStream fr = new System.IO.FileStream(HttpContext.Current.Server.MapPath(filmanagerpath + guid),System.IO.FileMode.Create) ) {
				fr.Write(dati,0,dati.Length);
			}
			//qui codice per il db.
			string insQuery = "insert into {0}admfilemanager ( pname, srcname, related, author, filesize, data_mod, data_ins, instanceid, group_name) VALUES(" +
				" '{1}','{2}', '{3}',{4},'{5}',Now(),Now(),{6},'{7}'   " +
				");";
			int reso = dclass.Helper_NonQuery(string.Format( insQuery, TablePrefix, 
			                                                SqlText(filename), 
			                                                SqlText(guid), 
			                                                SqlText(related),
			                                                SqlText(author),
			                                                dati.Length.ToString(), 
			                                                instance, 
			                                                SqlText(groupname) ));
			if(reso>0) return "OK";
			else {
				_DeleteFile(guid);
			}
			return "ND";
		}
		
		private void _DeleteFile(string guid) {
			string path = HttpContext.Current.Server.MapPath(filmanagerpath + guid)	;
			if(!System.IO.File.Exists(path)) return;
			System.IO.File.Delete(path);
		}
		
		[WebMethod]
		public string DeleteFile(string id) {
			object o = dclass.HStandard_SC("select srcname from "+TablePrefix+"admfilemanager where id='"+id+"' limit 1");
			string fileName = "";
			if(o==null) return "NF";
			if(o is byte[])
				fileName = System.Text.Encoding.UTF8.GetString((byte[]) o);
			else
				fileName = o.ToString();
			if(fileName.Trim().Length==0) return "NF";
			_DeleteFile(fileName);			
			int reso = dclass.Helper_NonQuery("delete from "+TablePrefix+"admfilemanager where id='"+id+"' limit 1");
			if(reso > 0 ) return "OK";
			return "NO";
		}
		
		[WebMethod]
		public string EditFile(string id, string newName, string newGroup) {
			if(id.Trim().Length==0) return "0";
			if(newName.Trim().Length==0) return "0";
			id = HttpUtility.UrlDecode(id);
			newName = HttpUtility.UrlDecode(newName);
			newGroup = HttpUtility.UrlDecode(newGroup);
			string updQuery = "update {0}admfilemanager set  pname='{1}', data_mod=Now(), group_name = '{2}' " +
				" where id={3}  limit 1;  ";
			int reso = dclass.Helper_NonQuery(string.Format( updQuery, TablePrefix, SqlText(newName), SqlText(newGroup), id ));
			if(reso>0) return "OK";
			return "0";					
		}
	}
	
}
